package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.commons.CrmRedisKeys;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.enums.IntegralEnums;
import cc.linker.steplink.crm.commons.utils.StringUtil;
import cc.linker.steplink.crm.merchanth5.dao.GiveCouponsDao;
import cc.linker.steplink.crm.merchanth5.dao.RegisterActivityDao;
import cc.linker.steplink.crm.merchanth5.dao.ScoreActiveCacheDao;
import cc.linker.steplink.crm.merchanth5.dao.VipCustomerLogDao;
import cc.linker.steplink.crm.merchanth5.pojo.GiveCouponPo;
import cc.linker.steplink.crm.merchanth5.pojo.RegisterActivityPo;
import cc.linker.steplink.crm.merchanth5.pojo.coupon.CustomerCouponVo;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Author: CKQ
 * @DateTime: 2020/12/17 16:35
 * @Description: TODO
 */
@Service
@Slf4j
public class RegisterActivityService {
    @Autowired
    private RegisterActivityDao registerActivityDao;
    @Autowired
    private GiveCouponsDao giveCouponsDao;
    @Autowired
    private CustomerIntegralService customerIntegralService;
    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private SurvivalPushService survivalPushService;
    @Autowired
    private ScoreActiveCacheDao scoreActiveCacheDao;
    @Autowired
    private VipCustomerLogDao vipCustomerLogDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String SHARE_REGISTER_GIFT = "share_register_gift:";

    /**
     * @param orgId 机构ID
     * @Description：通过机构ID 获取注册有礼的列表
     * @DateTime：2020/12/17 16:20
     * @Params：
     * @Return：
     */
    public PageInfo<RegisterActivityPo> getRegisterActivityListByOrgId(String activityName, Integer status, Integer pageIndex, Integer pageSize, String orgId) {
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(this.registerActivityDao.getRegisterActivityListByOrgId(activityName, status, orgId));
    }

    /**
     * @param activityId 活动ID
     * @Description：获取活动详情
     * @DateTime：2020/12/18 11:27
     * @Params：
     * @Return：
     */
    public RegisterActivityPo getRegisterActivityInfo(String activityId, CouponCustomerInfo couponCustomerInfo) {
        RegisterActivityPo registerActivityPo = this.registerActivityDao.getRegisterActivityInfo(activityId);
        if (!StringUtils.isEmpty(registerActivityPo.getActivityId())) {
            List<GiveCouponPo> giveCouponPos = this.giveCouponsDao.getGiveCouponsByVipId(registerActivityPo.getActivityId());
            Map<String, Object> param = new HashMap<>();
            for (GiveCouponPo giveCouponPo : giveCouponPos) {
                param.put("couponId", giveCouponPo.getCouponId());
                Map<String, Object> couponInfo = (Map) couponRequest.doRequest("coupon-detail", param, couponCustomerInfo);
                if (couponInfo != null) {
                    giveCouponPo.setName((String) couponInfo.get("name"));
                    giveCouponPo.setInventory(String.valueOf((Integer) couponInfo.get("maxPublishNum") - (Integer) couponInfo.get("publishNum")));
                }
            }
            registerActivityPo.setGiveCouponPoList(giveCouponPos);
        }
        return registerActivityPo;
    }

    /**
     * @Description：验证添加编辑的时候参数是否正确
     * @DateTime：2020/12/17 16:48
     * @Params：
     * @Return：
     */
    private RegisterActivityPo verifyParams(RegisterActivityPo registerActivityPo) {
        if (StringUtils.isEmpty(registerActivityPo.getActivityName())) {
            throw GlobalException.build("活动名称不能为空！");
        }
        if (StringUtils.isEmpty(registerActivityPo.getStartTime()) || StringUtils.isEmpty(registerActivityPo.getEndTime())) {
            throw GlobalException.build("活动时间不能为空");
        }
        if (registerActivityPo.getActivityType() == null) {
            throw GlobalException.build("请选择注册场景！");
        }
        if (registerActivityPo.getIntegral() == null) {
            registerActivityPo.setIntegral(0);
        }
        if (registerActivityPo.getGrowth() == null) {
            registerActivityPo.setGrowth(0);
        }
        if (registerActivityPo.getIntegral().equals(0)
                && registerActivityPo.getGrowth().equals(0)
                && (registerActivityPo.getGiveCouponPoList() == null || registerActivityPo.getGiveCouponPoList().size() == 0
        )) {
            throw GlobalException.build("请选择奖励！");
        }
        return registerActivityPo;
    }


    /**
     * @param registerActivityPo 注册有礼实体
     * @param registerActivityPo 活动实体
     * @Description：添加注册有礼活动
     * @DateTime：2020/12/17 16:21
     * @Params：
     * @Return：
     */
    public void insertRegisterActivity(RegisterActivityPo registerActivityPo) {
        this.verifyParams(registerActivityPo);
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        registerActivityPo.setActivityId(id);
        if (this.registerActivityDao.insertRegisterActivity(registerActivityPo) > 0) {
            if (registerActivityPo.getGiveCouponPoList() != null && registerActivityPo.getGiveCouponPoList().size() > 0) {
                registerActivityPo.getGiveCouponPoList().forEach(x -> {
                    x.setVipId(id);
                });
                this.giveCouponsDao.insert(registerActivityPo.getGiveCouponPoList());
            }
        }
    }

    /**
     * @param registerActivityPo 活动实体
     * @Description：编辑活动
     * @DateTime：2020/12/17 16:49
     * @Params：
     * @Return：
     */
    public void updateRegisterActivity(RegisterActivityPo registerActivityPo) {
        this.verifyParams(registerActivityPo);
        if (this.registerActivityDao.updateRegisterActivity(registerActivityPo) > 0) {
            this.giveCouponsDao.removeAllByVipId(registerActivityPo.getActivityId());
            if (registerActivityPo.getGiveCouponPoList() != null && registerActivityPo.getGiveCouponPoList().size() > 0) {
                registerActivityPo.getGiveCouponPoList().forEach(x -> {
                    x.setVipId(registerActivityPo.getActivityId());
                });
                this.giveCouponsDao.insert(registerActivityPo.getGiveCouponPoList());
            }
        }
    }

    /**
     * @param activityId 活动ID
     * @param status     状态0暂停 1启用
     * @Description：编辑是否启用
     * @DateTime：2020/12/17 16:50
     * @Params：
     * @Return：
     */
    public void updateRegisterActivityStatus(String activityId, Integer status) {
        if (activityId == null) {
            throw GlobalException.build("活动ID参数不能为空！");
        }
        if (status == null || (!status.equals(0) && !status.equals(1))) {
            throw GlobalException.build("活动状态参数不正确！");
        }
        this.registerActivityDao.updateRegisterActivityStatus(activityId, status);
    }

    /**
     * @param activityId 活动ID
     * @Description：删除注册活动
     * @DateTime：2020/12/17 16:54
     * @Params：
     * @Return：
     */
    public void deleteRegisterActivity(String activityId) {
        if (activityId == null) {
            throw GlobalException.build("活动ID参数不能为空！");
        }
        this.registerActivityDao.deleteRegisterActivity(activityId);
    }

    /**
     * @Description：注册有礼赠送
     * @DateTime：2020/12/18 15:44
     * @Params：
     * @Return：
     */
    public List<CustomerCouponVo> registerAward(String customerId, String orgId, String pid) {
        List<CustomerCouponVo> customerCouponVos = new ArrayList<>();
        List<CustomerCouponVo> shareGiftPos = new ArrayList<>();
        List<RegisterActivityPo> registerActivityPos = this.registerActivityDao.getRegisterActivityListByOrgId(null, 1, orgId);
        if (registerActivityPos != null && registerActivityPos.size() > 0) {
            for (RegisterActivityPo registerActivityPo : registerActivityPos) {
                //赠送用户  如果是注册用当前注册用户，如果是邀请注册 用分享人
                String giveCustomerId = registerActivityPo.getActivityType().equals(0) ? customerId : (customerId.equals(pid) ? "" : pid);

                //如果赠送人为空 则直接跳过不赠送
                if (StringUtils.isEmpty(giveCustomerId)) {
                    continue;
                }

                String act = "注册赠送";
                Integer scoreType = 13;
                if (!registerActivityPo.getActivityType().equals(0)) {
                    act = "邀请注册赠送";
                    scoreType = 10;
                }
                CustomerCouponVo IntegralGift = CustomerCouponVo.builder().build();
                CustomerCouponVo growthGift = CustomerCouponVo.builder().build();
                //积分赠送
                if (registerActivityPo.getIntegral() != null
                        && registerActivityPo.getIntegral() > 0
                        && registerActivityPo.getIsIntegral().equals(1)) {
                    this.customerIntegralService.addIntegralCustomerLog(giveCustomerId, act, IntegralEnums.customerScore.toString(), registerActivityPo.getIntegral().toString(), IntegralEnums.customerScore.toString(), orgId);
                    IntegralGift.setType(4);
                    IntegralGift.setName(registerActivityPo.getIntegral() + "积分");
                    if (registerActivityPo.getActivityType().equals(0)) {
                        //当前注册用户礼物
                        customerCouponVos.add(IntegralGift);
                    } else {
                        //分享用户礼物
                        shareGiftPos.add(IntegralGift);
                    }
                    this.setLog(giveCustomerId, registerActivityPo.getIntegral(), scoreType, act, 1);
                }

                //成长值赠送
                if (registerActivityPo.getGrowth() != null
                        && registerActivityPo.getGrowth() > 0
                        && registerActivityPo.getIsGrowth().equals(1)) {
                    this.customerIntegralService.addIntegralCustomerLog(giveCustomerId, act, IntegralEnums.customerGrowthScore.toString(), registerActivityPo.getGrowth().toString(), IntegralEnums.mallSystem.toString(), orgId);
                    growthGift.setType(5);
                    growthGift.setName(registerActivityPo.getGrowth() + "成长值");

                    if (registerActivityPo.getActivityType().equals(0)) {
                        //当前注册用户礼物
                        customerCouponVos.add(growthGift);
                    } else {
                        //分享用户礼物
                        shareGiftPos.add(growthGift);
                    }
                    this.setLog(giveCustomerId, registerActivityPo.getGrowth(), scoreType, act, 0);
                }

                List<GiveCouponPo> giveCouponPos = this.giveCouponsDao.getGiveCouponsByVipId(registerActivityPo.getActivityId());
                if (giveCouponPos != null && giveCouponPos.size() > 0 && registerActivityPo.getIsCoupon().equals(1)) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("couponList", giveCouponPos);
                    CouponCustomerInfo customerInfo = CouponCustomerInfo
                            .builder()
                            .customerId(giveCustomerId)
                            .orgId(orgId)
                            .customerName("")
                            .customerPhone("")
                            .cover("")
                            .sourceUserId("")
                            .build();
                    Object result = this.couponRequest.doRequest("give-coupons", param, customerInfo);
                    List<String> consumptionIds = (List<String>) result;
                    if (consumptionIds != null && consumptionIds.size() > 0) {
                        param.put("consumptionIds", consumptionIds);
                        result = this.couponRequest.doRequest("customer-coupon-list", param, customerInfo);
                        List<JSONObject> customerCouponList = (List<JSONObject>) result;
                        if (registerActivityPo.getActivityType().equals(0)) {
                            for (JSONObject couponVo : customerCouponList) {
                                customerCouponVos.add(JSON.toJavaObject(couponVo, CustomerCouponVo.class));
                            }
                        } else {
                            for (JSONObject couponVo : customerCouponList) {
                                shareGiftPos.add(JSON.toJavaObject(couponVo, CustomerCouponVo.class));
                            }
                        }
                    }
                }
            }
            //如果分享人不为空，需要调用分享送积分成长值的任务
            if (!StringUtils.isEmpty(pid)) {
                this.setCustomerGifts(shareGiftPos, pid);
            }

            return customerCouponVos;
        }
        return null;
    }

    /**
     * @Description：注册分享设置的积分任务和
     * @DateTime：2021/1/22 8:49
     * @Params：
     * @Return：
     */
    public void registerShareAward(String orgId, String pid) {
        if (StringUtils.isEmpty(pid)) {
            return;
        }
        //如果有分享人，分享邀请次数+1
        String integralKey = CrmRedisKeys.INVITE_REGISTER + IntegralEnums.customerScore.toString() +"_"+ pid;
        String growthKey = CrmRedisKeys.INVITE_REGISTER + IntegralEnums.customerGrowthScore.toString() +"_"+ pid;
        this.stringRedisTemplate.opsForValue().increment(integralKey, 1);
        this.stringRedisTemplate.opsForValue().increment(growthKey, 1);

        String inviteIntegralNumStr = this.stringRedisTemplate.opsForValue().get(integralKey);
        String inviteGrowthNumStr = this.stringRedisTemplate.opsForValue().get(growthKey);

        Integer inviteIntegralNum = 0;
        Integer inviteGrowthNum = 0;
        if (!StringUtils.isEmpty(inviteIntegralNumStr)) {
            inviteIntegralNum = Integer.valueOf(inviteIntegralNumStr);
        }
        if (!StringUtils.isEmpty(inviteGrowthNumStr)) {
            inviteGrowthNum = Integer.valueOf(inviteGrowthNumStr);
        }
        List<Map<String, Object>> scoreActiveList = scoreActiveCacheDao.getScoreAct("share", "register", orgId);
        if (scoreActiveList != null && scoreActiveList.size() > 0) {
            for (Map<String, Object> activeMap : scoreActiveList) {
                Map<String, Object> rule = JSON.parseObject(activeMap.get("rule").toString(), Map.class);
                if (!StringUtils.isEmpty(rule)) {
                    Integer score = Integer.valueOf(rule.get("val2").toString());
                    //积分
                    if (activeMap.get("type").toString().equals("1") && Integer.valueOf(rule.get("val1").toString()).equals(inviteIntegralNum)) {
                        this.customerIntegralService.addIntegralCustomerLog(pid,
                                "邀请注册赠送",
                                IntegralEnums.customerScore.toString(),
                                score.toString(),
                                IntegralEnums.mallSystem.toString(),
                                orgId);
                        this.setLog(pid, score, 10, "邀请注册赠送", 1);
                        this.stringRedisTemplate.delete(integralKey);
                    }
                    if (activeMap.get("type").toString().equals("2") && Integer.valueOf(rule.get("val1").toString()).equals(inviteGrowthNum)) {
                        this.customerIntegralService.addIntegralCustomerLog(pid,
                                "邀请注册赠送",
                                IntegralEnums.customerGrowthScore.toString(),
                                score.toString(),
                                IntegralEnums.mallSystem.toString(),
                                orgId);
                        this.setLog(pid, score, 10, "邀请注册赠送", 0);
                        this.stringRedisTemplate.delete(growthKey);
                    }
                }
            }
        }
    }

    /**
    * @Description：添加日志
    * @DateTime：2021/1/22 9:14
    * @Params：
    * @Return：
    */
    private void setLog(String giveCustomerId,Integer score,Integer scoreType,String act,Integer giveType) {
        if (giveType.equals(1)) {
            Map<String, Object> logParam = new HashMap<>();
            logParam.put("scoreLogId", UUID.randomUUID().toString());
            logParam.put("customerId", giveCustomerId);
            logParam.put("scoreValue", score);
            logParam.put("scoreType", scoreType);
            logParam.put("actionRemark", act + score + "积分");
            logParam.put("sendWx", 1);
            scoreActiveCacheDao.addLog(logParam);
        } else {
            Map<String, Object> log = new HashMap<String, Object>();
            log.put("logId", UUID.randomUUID().toString());
            log.put("customerId", giveCustomerId);
            log.put("growthValue", score);
            log.put("growthType", scoreType);
            log.put("actionRemark", act + score + "成长值");
            vipCustomerLogDao.addGrowth(log);
        }
    }

    /**
     * @Description：设置赠送礼物
     * @DateTime：2020/12/29 20:28
     * @Params：
     * @Return：
     */
    private void setCustomerGifts(List<CustomerCouponVo> gifts, String customerId) {
        if (gifts == null || gifts.size() == 0) {
            return;
        }
        String giftStr = this.stringRedisTemplate.opsForValue().get(SHARE_REGISTER_GIFT + customerId);
        if (!StringUtils.isEmpty(giftStr)) {
            List<CustomerCouponVo> customerCouponVos = JSON.parseArray(giftStr, CustomerCouponVo.class);
            if (customerCouponVos != null && customerCouponVos.size() > 0) {
                gifts.addAll(customerCouponVos);
            }
        }
        this.stringRedisTemplate.opsForValue().set(SHARE_REGISTER_GIFT + customerId, JSON.toJSONString(gifts, SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteMapNullValue));
    }

    /**
     * @Description：获取用户的礼物
     * @DateTime：2020/12/29 20:22
     * @Params：
     * @Return：
     */
    public List<CustomerCouponVo> getGiftList(String customerId) {
        String giftStr = this.stringRedisTemplate.opsForValue().get(SHARE_REGISTER_GIFT + customerId);
        if (!StringUtils.isEmpty(giftStr)) {
            this.stringRedisTemplate.delete(SHARE_REGISTER_GIFT + customerId);
            return JSON.parseArray(giftStr, CustomerCouponVo.class);
        } else {
            return new ArrayList<>();
        }
    }
}